# -*- coding=utf-8 -*-
# Created Time: 2016年08月30日 星期二 16时05分45秒
# File Name: lib_re.py

"""
用到的各种正则
"""

import re, time


def regex_char_trans(val):
    """ 正则匹配的时候将正则特殊字符转义 """

    reg_list = ['\\', '+', '*', '?', '[', '^', ']', '$',
            '(', ')', '{', '}', '=', '!', '<', '>', '|', ':', '-'
        ]

    for i in reg_list:
        if i in val:
            val = val.replace(i, '\\'+i)

    val = val.replace('.', '\\.')
    return val


def between_quota(val):
    """ 提取字符串中 双引号 之间的值 """

    pattern = re.compile('"(.*)"')

    value = pattern.findall(val)

    return value

def between_underline_dollar(val):
    """ 下划线和美元符号 之间的值 """

    # 要匹配的是变量名，长度在 1-15 之间
    pattern = re.compile('\$(.{1,15})_')

    value = pattern.findall(val)

    return value

def format_add_0(val):

    return '%04d' % int(val)

def high2max(high):
    """ 处理版本号为可比较大小的字符串

        max_str 应该是一个16位的字符串
    """

    max_str = ''
    foo = high.split('.')

    for f in foo:
        max_str += format_add_0(f)

    return max_str


def check_filename(filename):
    """ 校验文件名格式是否正确并返回文件信息 """

    l = filename[:-4].split('_')
    if len(l) != 4 or '' in l:
        return False, {}
    sn_ids_str, ver_from, ver, create_time = l[0], l[1], l[2], l[3]

    sn_ids = sn_ids_str.split(',')
    if '' in sn_ids:
        return False, {}
    try:
        # if int(ver_from.replace('.','')) >= int(ver.replace('.','')):
        #     callback((False, 'ver error!'))
        #     return
        if compareversion(ver_from, ver) >= 0:
            return False, {}
    except:
        return False, {}

    info = {
        'filename':     filename,           # 文件名
        'sn_ids':       sn_ids,             # 包含的sn ids
        'sn_ids_str':   sn_ids_str,
        'ver_from':     ver_from,           # 上一个版本的版本号
        'ver':          ver,                # 版本号
        'create_time':  create_time,        # 创建包的时间
        'ts':           int(time.time()),   # 时间戳
    }
    return True, info


def main():

    #val = 'E11000 duplicate key error index: fota.seed.$name_1  dup key: { : "name01" }'
    #value = between_quota(val)
    #value = between_underline_dollar(val)

    #value = format_add_0(1)
    #print 'value between quota: ', value

    '''
    file_name = 'V05S74_0.7.0.0_0.7.1.26_20160714.zip'
    status, info = check_filename(file_name)

    print 'status: ', status
    print 'info: ', info
    '''

    data = high2max('0.7.1.26')

if __name__ == '__main__':
    main()


